//$(document).ready(function() {
var user_IaaS = function() {

    function getImage(callback) {
        var images = [];
        var siteName = $('#preferredSiteComboBox')[0].value;
        $.post('/' + siteName + '/iaas/execute_wait/iaas.get_image_info.json', {
            user: userid
        },
        function(serverResponse) {
            for (var i = 0; i < serverResponse[1].length; i++) {
                var image = new Option(serverResponse[1][i], serverResponse[1][i]);
                images.push(image);
            }
            callback(images);
        },
        'json');
    };
    function userloadImage(images) {
        $("#userVMCreationImageField")[0].options.length = 0;
        for (var i = 0; i < images.length; i++) {
            $("#userVMCreationImageField")[0].options.add(images[i]);
        }
    };
    function userloadSites() {
        for (var i = 0; i < allsites.length; i++) {
            var sites = new Option(allsites[i], allsites[i]);
            $("#preferredSiteComboBox")[0].options.add(sites);
        }
    };
    function actResult(status, act, vmid) {
	var j,vm,node;
        if (status == 'success') {
            alert(act + ' ' + vmid + ' success');
            if (act == 'delete' || act == 'shutdown') {
                for (j = $('#userVMCreationTable').dataTable().fnSettings().aoData.length - 1; j >= 0; j--) {
                    vm = $('#userVMCreationTable').dataTable().fnSettings().aoData[j]._aData[0];
                    if (vm == vmid) {
                        node = $('#userVMCreationTable').dataTable().fnGetNodes(j);
                        $('#userVMCreationTable').dataTable().fnDeleteRow(node);
                    }
                }
            }
            else {
                for (j = $('#userVMCreationTable').dataTable().fnSettings().aoData.length - 1; j >= 0; j--) {
                    vm = $('#userVMCreationTable').dataTable().fnSettings().aoData[j]._aData[0];
                    if (vm == vmid) {
                        node = $('#userVMCreationTable').dataTable().fnGetNodes(j);
                        var newState = '';
                        if (act === 'suspend') newState = 'SUSPENDED';
                        if (act === 'resume') newState = 'RUNNING';
                        if (act === 'stop') newState = 'STOPPED';
                        $('#userVMCreationTable').dataTable().fnUpdate(newState, node, 7, 0);
                    }
                }
            }
        }
        else {
            alert(vmid + ' ' + status);
        }
    };
    function userAct(siteName, act, vmid, callback) {
        if (act == 'delete') {
            $.post('/' + siteName + '/iaas/execute_wait/iaas.vm_delete.json', {
                user: userid,
                vm_id: vmid
            },
            function(serverResponse) {
                if (serverResponse[0] === true) {
                    callback('success', act, vmid);
                }
                else {
                    callback(serverResponse[0] + serverResponse[1], act, vmid);
                }
            },
            'json');
        }
        else {
            $.post('/' + siteName + '/iaas/execute_wait/iaas.vm_action.json', {
                user: userid,
                action: act,
                vm_id: vmid
            },
            function(serverResponse) {
                if (serverResponse[0] == true) {
                    callback('success', act, vmid);
                }
                else {
                    callback(serverResponse[0] + serverResponse[1], act, vmid);
                }
            },
            'json');
        }
    };
    function useraction() {
        var anSelected = fnGetSelected(userVMCreationTable);
        var a = $('td', anSelected);
        if (a.length == 0) {
            alert("please select one row!");
            return 0;
        }
        act = $("#userVMAction")[0].value;
        for (var j = 0; j < anSelected.length; j++) { (function(selectedVM) {
                var vmid = $($('td', selectedVM)[0]).text();
                var siteName = $($('td', selectedVM)[5]).text();
                userAct(siteName, act, vmid, actResult);
                /*if (act=="delete") 
			{
				var siteName=$($('td',selectedVM)[5]).text();
				var deleteResult=userDeleteVM(siteName,vmid);
				if(deleteResult)
				{       
					alert("delete  "+vmid+"  success");
					userVMCreationTable.fnDeleteRow(selectedVM);
				}
				else
				{}
			}
			else if(act=="migrate") {}
			else
			{		
				var siteName=$($('td',selectedVM)[5]).text();
				var  userActResult=userAct(siteName,act,vmid);
				if(userActResult)
				{
					(act+"  "+vmid+"  success");  
				}
				else 
				{}

			}*/

            })(anSelected[j]);
        }
    };
    function getUserIaasVMs(callback) {
        for (var j = 0; j < allsites.length; j++) { (function(siteName) {
                $.get('/' + siteName + '/iaas/execute_wait_cacheable/iaas.get_vmpool_info.json?user_name=' + userid, {},
                function(serverResponse) {
                    var hostMachine;
                    var vmid;
                    var vmip;
                    var vmport;
                    var ipv6address;
                    var vmname;

                    var vcpus;

                    var memory;

                    var stat;
                    var starttime;
                    var tableData = [];
                    if (serverResponse[0] === false) {
                        return;
                    }
                    for (var i = 0; i < serverResponse[1].length; i += 1) {

                        vmid = serverResponse[1][i].guid;

                        vmname = serverResponse[1][i].name;
                        if (serverResponse[1][i].ipv6) {
                            ipv6address = serverResponse[1][i].ipv6;
                        }
                        else {
                            ipv6address = 'NOT AVAILABLE';
                        }
                        vmip = serverResponse[1][i].ip;
                        vmport = serverResponse[1][i].port;
                        vcpus = serverResponse[1][i].cpu;

                        memory = serverResponse[1][i].memory; //1024;
                        hostMachine = serverResponse[1][i].hostMachine;
                        stat = serverResponse[1][i].stat;
                        starttime = serverResponse[1][i].stime;
                        tableData.push([vmid, vmname, ipv6address, vcpus, memory, siteName, starttime, stat]);

                    }
                    callback(siteName, tableData);
                },
                'json');
            })(allsites[j]);
        }
    };
    function loaduserIaasVMs(siteName, tableData) {
        for (var j = $('#userVMCreationTable').dataTable().fnSettings().aoData.length - 1; j >= 0; j--) {
            var name = $('#userVMCreationTable').dataTable().fnSettings().aoData[j]._aData[5];
            if (name == siteName) {
                var node = $('#userVMCreationTable').dataTable().fnGetNodes(j);
                $('#userVMCreationTable').dataTable().fnDeleteRow(node);
            }
        }
        $('#userVMCreationTable').dataTable().fnAddData(tableData);
    };
    function userCreateResult(status) {
        alert(status);
        setTimeout(getUserIaasVMs(loaduserIaasVMs), 2000);
    };
    function userCreateVM(siteName, vm, vcpus, mirror, vmmemory, callback) {
        $.post('/' + siteName + '/iaas/execute_wait/iaas.vm_create.json', {
            user_name: userid,
            memory: vmmemory,
            vcpu: vcpus,
            image_dir: mirror,
            count: vm
        },
        function(serverResponse) {
            if (serverResponse[0]) {
                callback('create vm succeed');
            }
            else {
                callback(serverResponse[0] + serverResponse[1]);
            }
        },
        'json');
    };

    $('#userIaaSVMCreationDialog').dialog({
        modal: false,
        autoOpen: false,
        title: 'Create VM',
        width: 450,
        buttons: {
            Confirm: function(event) {
                var vm = $("#userVMCreationAmountField")[0].value;
                var mirror = $("#userVMCreationImageField")[0].value;
                var vcpus = $("#userVMCreationVCPUField")[0].value;
                var vmmemory = $("#userVMCreationMemoryField")[0].value;
                var isNumber = /^[1-9]+[0-9]*$/;
                if (isNumber.test(vm) === false) {
                    alert('Amount is a number!');
                    return;
                }
                if (isNumber.test(vcpus) === false) {
                    alert('VCPUs is a number!');
                    return;
                }
                if (vm > 50) {
                    alert('the Amount is not more than 50');
                    return;
                }
                if (vcpus > 24) {
                    alert('the VCPUs is not more  than 24');
                    return;
                }
                var info = 'NOTE:Your request will be sent to site ' + $('#preferredSiteComboBox')[0].value + ' If you want to choose other sites, please click the [site] button on top right cornor.' + ' Are you sure to create the VM?';
                $("#craneModalDialogContent").text(info);
                $('#craneModalDialog').dialog({
                    buttons: {
                        Confirm: function() {
                            var siteName = $("#preferredSiteComboBox")[0].value;
                            userCreateVM(siteName, vm, vcpus, mirror, vmmemory, userCreateResult);
                            $(this).dialog('close');

                        },

                        Cancel: function() {
                            $(this).dialog('close');
                        }
                    }
                }).dialog('open');
                $(this).dialog('close');
            },
            Cancel: function() {
                $(this).dialog('close');
            }
        }
    });

    $('#preferredSiteComboBox').change(function() {
        getImage(userloadImage);
    });
    $("#userVMCreateButton").click(function(event) {
        $('#userIaaSVMCreationDialog').dialog('open');
    });
    $("#userVMActionConfirmButton").click(function(event) {
        var anSelected = fnGetSelected(userVMCreationTable);
        var a = $('td', anSelected);
        if (a.length === 0) {
            alert("please select one row!");
            return 0;
        }
        var vmid = $(a[0]).text();
        act = $("#userVMAction")[0].value;
        $("#craneModalDialogContent").text("are you sure to " + act);
        $('#craneModalDialog').dialog({
            buttons: {
                Confirm: function() {
                    useraction();
                    $(this).dialog('close');
                },

                Cancel: function() {
                    $(this).dialog('close');
                }
            }
        }).dialog('open');

    });
    $("#userVMActionRefreshButton").click(function(event) {
        getUserIaasVMs(loaduserIaasVMs);
    });
    userloadSites();
    getImage(userloadImage);
    getUserIaasVMs(loaduserIaasVMs);
    /*window.setInterval(function(){
	getUserIaasVMs(loaduserIaasVMs);
	},60000);*/
    //});
};
